<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-03-26 01:16:12
 * @LastEditors: Sam
 * @LastEditTime: 2022-10-19 13:58:38
 */
declare (strict_types=1);

namespace app\common\exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\PDOException;
use think\exception\ErrorException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use app\common\traits\ResponseJson;
use think\facade\Log;

class ExceptionHandle extends Handle
{
  
    use ResponseJson;
   /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        $this->report($e);
    try {
        $dataArr = [
            'url'      => $request->url() ?? 'unknown',
            'file'     => $e->getFile() ?? 'unknown',
            'line'     => $e->getLine() ?? 0,
            'message'  => $e->getMessage() ?? 'Unknown error',
            'request'  => method_exists($request, 'param') ? ($request->param() ?? []) : [],
            'ip'       => $request->ip() ?? '0.0.0.0',
            'method'   => $request->method() ?? 'UNKNOWN',
            'datetime' => date('Y-m-d H:i:s'),
        ];
        
        // 使用模板字符串简化日志格式
        $log = <<<LOG
====== 接口错误日志 ======
时间：{$dataArr['datetime']}
方法：{$dataArr['method']}
请求URL：{$dataArr['url']}
IP地址：{$dataArr['ip']}
文件：{$dataArr['file']}
行号：{$dataArr['line']}
错误信息：{$dataArr['message']}
请求参数：
LOG . json_encode($dataArr['request'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n" . 
"===========================\n";
        
        Log::error($log);
    } catch (Throwable $logError) {
        // 即使日志记录失败也不影响主流程
        Log::error('记录错误日志时发生异常: ' . $logError->getMessage());
    }
        // 其他错误交给系统处理
        if ($e instanceof ValidateException)
            return $this->error($e->getMessage());
        else if ($e instanceof DataNotFoundException)
            return $this->error(isDebug() ? $e->getMessage() : '数据不存在',500, ['code' => $e->getCode(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]);
        else if ($e instanceof ModelNotFoundException)
            return $this->error(isDebug() ? $e->getMessage() : '模型不存在',500, ['code' => $e->getCode(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]);
        else if ($e instanceof PDOException)
            return $this->error(isDebug() ? $e->getMessage() : '数据库操作失败',500, ['code' => $e->getCode(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]);
        else if ($e instanceof ErrorException)
            return $this->error(isDebug() ? $e->getMessage() : '系统错误',500, ['code' => $e->getCode(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]);
        else if ($e instanceof \PDOException)
            return $this->error(isDebug() ? $e->getMessage() : '数据库连接失败',500, ['code' => $e->getCode(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]);
        else
            return $this->error($e->getMessage(), 500, ['code' => $e->getCode(), 'line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]);
        return parent::render($request, $e);
    }
}
